package mediaplayermanager;

/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                       (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.

    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/

    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews

    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.StringTokenizer;

import org.knopflerfish.service.log.LogRef;

public class MPlayerManagerThread extends Thread
{
	private static final String MEDIA_NORMAL = "NM";
	private static final String BLANK_SCREEN = "BL";
	private static final String LOCATION_SCREEN = "LC";
	private static final String END_OF_MEDIA_STREAM = "DONE";
	private static final String MEDIA_NOT_AVL = "Media Not Avlbl";
	private static final String NOT_KNOWN = "Not Known";
	private static final String PLAYED_FULLY = "Played Fully";
	private static final String MEDIA_INTERRUPT = "Media Interrupt";
	private static final String NOT_PLAYED = "Not Played";
	private static final String ZERO_DURATION = "Zero Duration";
	private static final String PLAY_ERROR = "Play Error";
	private DBConnectionPool dbConnectionPool;
	private boolean running = true;
	private Process mplayerProcess;
	private BufferedReader mplayerStdOut;
	private InputStream mplayerStdoutRaw; 
	private MPlayerManagerConfig config;
	private LogRef log;
	protected boolean playCurrentMediaSet = false;
	protected String loopTillNextTriggerFlag = "T";
	private String persistentDataQuery = "SELECT current_route_code, current_trigger_descriptor_id FROM persistent_data";
	private String mediaPlayerQueueQuery = "SELECT media_type, abs_media_path, media_duration, media_code, loop_till_next_trigger_flag, media_seq_no, trigger_type, node_code, relative_media_path  FROM media_player_queue ORDER BY media_seq_no";
	private String lastMediaPlayedQuery = "SELECT trigger_desc_id, med_seq_no FROM last_media_played";
	private String lastMediaInsert = "INSERT INTO last_media_played VALUES(1, ?,?)";
	private String lastMediaUpdate = "UPDATE last_media_played SET trigger_desc_id=?, med_seq_no=?";
	private String mediaPlayLogInsert = "INSERT INTO media_play_log VALUES(default,?,?,?,?,?,?,?,?,?,?,default)";
	private String playLocationquery = "SELECT id FROM play_location";
	private String playLocationInsert = "INSERT INTO play_location VALUES(1, 'F', 0)";
	private String playLocationUpdate = "UPDATE play_location SET play=?, duration=?";
	private String currLatLongQuery = "SELECT lng, lat FROM curr_lat_long";
	
	public MPlayerManagerThread()
	{
		try
		{
			Runtime.getRuntime().exec("killall -9 mplayer");
			log = new LogRef(Activator.bc);
			config = MPlayerManagerConfig.getConfig();
			dbConnectionPool = DBConnectionPool.getInstance(config.getJdbcConnectionURI());
			Connection conn = null;
			PreparedStatement preparedStmt1 = null;
			PreparedStatement preparedStmt2 = null;
			ResultSet rs1 = null;
			try 
	    	{
				conn = dbConnectionPool.getConnection();
				conn.setAutoCommit(false);
				preparedStmt1 = dbConnectionPool.getPreparedStmt(conn, playLocationquery);
				rs1= preparedStmt1.executeQuery();
		    	if (rs1.next() == false)
		    	{
		    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, playLocationInsert);
		    		preparedStmt2.executeUpdate();
			    	preparedStmt2.close();
			    	preparedStmt2 = null;
		    	}
		    	rs1.close();
		    	rs1 = null;
		    	preparedStmt1.close();
		    	preparedStmt1 = null;
		    	conn.commit();
		    	conn.close();
		    	conn = null;
	    	}
	    	catch (Exception e) 
			{
				System.out.println("Error while starting MPlayerManagerThread thread");
	    		e.printStackTrace();
	    		throw e;
			}
			finally
			{
				if (rs1 != null)
	    		{
	    			try {rs1.close();} catch (SQLException e) {} 
	    			rs1 = null;
	    		}
	    		if (preparedStmt1 != null)
	    		{
	    			try {preparedStmt1.close();} catch (SQLException e) {} 
	    			preparedStmt1 = null;
	    		}
	    		if (preparedStmt2 != null)
	    		{
	    			try {preparedStmt2.close();} catch (SQLException e) {} 
	    			preparedStmt2 = null;
	    		}
				if (conn != null)
				{
					try {conn.close();} catch (SQLException e) {}
					conn = null;
				}
			}
			
		}
		catch(Exception e)
		{
			System.out.println("MPlayerManagerThread failed to start. Application needs to be restarted");
			e.printStackTrace();
		}
	}

	public void run()
	{
		try {Thread.sleep(config.getMediaPlayerStartDelaySecs()*1000);} catch (InterruptedException e) {}
		while(running == true)
		{
			fetchAndPlayMediaFromQueue();
		}
	}

	private void fetchAndPlayMediaFromQueue()
	{
		Connection conn = null;
		PreparedStatement preparedStmt1 = null;
		PreparedStatement preparedStmt2 = null;
		PreparedStatement preparedStmt3 = null;
		PreparedStatement preparedStmt4 = null;
		PreparedStatement preparedStmt5 = null;
		PreparedStatement preparedStmt6 = null;
		PreparedStatement preparedStmt7 = null;
		PreparedStatement preparedStmt8 = null;
		ResultSet rs1 = null;
		ResultSet rs2 = null;
		ResultSet rs3 = null;
		ResultSet rs4 = null;
		try 
    	{
			int currentMediaTriggerId =0;
			String currentRouteCode = "";
			conn = dbConnectionPool.getConnection();
    		preparedStmt1 = dbConnectionPool.getPreparedStmt(conn, persistentDataQuery);
	    	rs1 = preparedStmt1.executeQuery();
	    	if (rs1.next() == true)
	    	{
	    		currentRouteCode = rs1.getString(1);
	    		currentMediaTriggerId = rs1.getInt(2);
	    	}
	    	else
	    	{
	    		throw new Exception("Persistent data entry not available!!!");
	    	}
	    	rs1.close();
	    	rs1 = null;
	    	preparedStmt1.close();
	    	preparedStmt1 = null;
	    	conn.close();
	    	conn = null;

			Object [] mediaList = null;
			conn = dbConnectionPool.getConnection();
			preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, mediaPlayerQueueQuery);
			rs2 = preparedStmt2.executeQuery();
			rs2.last();
			int rowCount = rs2.getRow();
			if (rowCount == 0 )
			{
				playCurrentMediaSet = false;
				System.out.println("No media available for play");
		    	//Wait till new media set is added to media player queue
				synchronized(Activator.waitObject)
				{
					Activator.waitObject.wait();
				}
			}
			else
			{
				playCurrentMediaSet = true;
				rs2.beforeFirst();
    			mediaList = new Object[rowCount];    
    			int counter = 0;
    			while(rs2.next() == true)
    			{
	    			String[] mediaInfo = new String[9];
    				mediaInfo[0] = rs2.getString(1); //mediaType
    				mediaInfo[1] = rs2.getString(2); //absMediaPath 
    				mediaInfo[2] = String.valueOf(rs2.getInt(3)); //mediaDuration
    				mediaInfo[3] = rs2.getString(4);  //mediaCode
    				mediaInfo[4] =  rs2.getString(5); //loopTillNextTriggerFlag
    				mediaInfo[5]= String.valueOf(rs2.getInt(6)); //mediaSeqNo
    				mediaInfo[6]= rs2.getString(7); //trigger
    				mediaInfo[7]= rs2.getString(8); //nodeCode
    				mediaInfo[8]= rs2.getString(9); //relative media path
    				mediaList[counter] = mediaInfo;
    				counter++;
    			}
			}
	    	rs2.close();
	    	rs2 = null;
	    	preparedStmt2.close();
	    	preparedStmt2 = null;
	    	conn.close();
	    	conn = null;
			whileloop: while (playCurrentMediaSet == true)
			{
				//System.out.println("beginning  while loop ");
				for (int i=0; i < mediaList.length; i++)
				{
					String[] mediaInfo = (String[]) mediaList[i];
 					String mediaType = mediaInfo[0];
    				String absMediaPath = mediaInfo[1];
    				int mediaDuration = Integer.parseInt(mediaInfo[2]);
    				String mediaCode = mediaInfo[3];
    				loopTillNextTriggerFlag =  mediaInfo[4];
    				int mediaSeqNo = Integer.parseInt(mediaInfo[5]);
    				String trigger = mediaInfo[6];
    				String nodeCode = mediaInfo[7];
    				String relativeMediaPath = mediaInfo[8];
    				log.debug("About to play media "+mediaCode + " with type "+mediaType);
    				if (mediaType.equals(MEDIA_NORMAL))
    				{
    					int lastPlayedMediaSeqNo = -1; 
    					int lastTriggerDescId = -1;
    					conn = dbConnectionPool.getConnection();
    					preparedStmt3 = dbConnectionPool.getPreparedStmt(conn, lastMediaPlayedQuery);
	    		    	rs3= preparedStmt3.executeQuery();
	    		    	if (rs3.next() == true)
	    		    	{
	    		    		lastTriggerDescId = rs3.getInt(1);
	    		    		lastPlayedMediaSeqNo = rs3.getInt(2);
	    		    		log.debug("lastPlayedMediaSeqNo: "+lastPlayedMediaSeqNo);
	    		    		log.debug("Current mediaSeqNo: "+mediaSeqNo);
	    		    	}
		    	    	rs3.close();
		    	    	rs3 = null;
		    	    	preparedStmt3.close();
		    	    	preparedStmt3 = null;
		    	    	conn.close();
		    	    	conn = null;
	    		    	if ((lastTriggerDescId == currentMediaTriggerId) && (mediaSeqNo <= lastPlayedMediaSeqNo) && loopTillNextTriggerFlag.equals("F"))
	    		    	{
	    		    		System.out.println("Already played/skipped this media "+absMediaPath);
	    		    	}
	    		    	else
	    		    	{
	    					String playedStatus = null;
	    					Timestamp startTime = new Timestamp(new Date().getTime());
	    					String startLongLat = "";
	    					conn = dbConnectionPool.getConnection();
	    		    		preparedStmt8 = dbConnectionPool.getPreparedStmt(conn, currLatLongQuery);
	    		    		rs4 = preparedStmt8.executeQuery();
	    		    	  	if (rs4.next() == true)
		    		    	{
	    		    	  		startLongLat = rs4.getDouble(1) + "," + rs4.getDouble(2);
		    		    	}
	    		    	  	rs4.close();
	    		    	  	rs4 = null;
	    			    	preparedStmt8.close();
			    	    	preparedStmt8 = null;
			    	    	conn.close();
			    	    	conn = null;
	    		    		File mediaFile = new File(absMediaPath);
	    	    			if (mediaFile == null || !mediaFile.exists())
	    	    			{
	    	    				System.out.println("Media File not found at: "+absMediaPath);
	    	    				playedStatus = MEDIA_NOT_AVL;
	    	    			}
	    	    			else
	    	    			{
	    	    				playedStatus = playMedia(absMediaPath, mediaDuration);
	    	    			}
    	    			
	    	    			if (playedStatus != null)
	    	    			{
	    	    				conn = dbConnectionPool.getConnection();
		    	    			if(playedStatus.equals(PLAYED_FULLY))
		    	    			{
		    	    				//Update the last_media_played table
		    	    				preparedStmt3 = dbConnectionPool.getPreparedStmt(conn, lastMediaPlayedQuery);
		    	    		    	rs3= preparedStmt3.executeQuery();
		    	    		    	if (rs3.next() == true)
		    	    		    	{
		    	    		    		lastTriggerDescId = rs3.getInt(1);
		    	    		    		lastPlayedMediaSeqNo = rs3.getInt(2);
		    	    		    		if ((lastTriggerDescId == currentMediaTriggerId) && (mediaSeqNo <= lastPlayedMediaSeqNo))
		    	    		    		{
		    	    		    			//do nothing
		    	    		    		}
		    	    		    		else
		    	    		    		{
		    		    		    		preparedStmt4 = dbConnectionPool.getPreparedStmt(conn, lastMediaUpdate);
		    		    		    		preparedStmt4.setInt(1, currentMediaTriggerId);
		    	    		    			preparedStmt4.setInt(2, mediaSeqNo);
		    		    		    		preparedStmt4.executeUpdate();
		    		    			    	preparedStmt4.close();
		    				    	    	preparedStmt4 = null;
		    	    		    		}
		    	    		    	}
		    	    		    	else
		    	    		    	{
		    	    		    		preparedStmt5 = dbConnectionPool.getPreparedStmt(conn, lastMediaInsert);
		    	    		    		preparedStmt5.setInt(1, currentMediaTriggerId);
		    	    		    		preparedStmt5.setInt(2, mediaSeqNo);
		    	    		    		preparedStmt5.executeUpdate();
		    	    			    	preparedStmt5.close();
		    			    	    	preparedStmt5 = null;
		    	    		    	}
		    		    	    	rs3.close();
		    		    	    	rs3 = null;
		    		    	    	preparedStmt3.close();
		    		    	    	preparedStmt3 = null;
		    	    			}
	    	    				String endLongLat = "";
		    		    		preparedStmt8 = dbConnectionPool.getPreparedStmt(conn, currLatLongQuery);
		    		    		rs4 = preparedStmt8.executeQuery();
		    		    	  	if (rs4.next() == true)
			    		    	{
		    		    	  		endLongLat = rs4.getDouble(1) + "," + rs4.getDouble(2);
			    		    	}
		    		    	  	rs4.close();
		    		    	  	rs4 = null;
		    			    	preparedStmt8.close();
				    	    	preparedStmt8 = null;

	    	    				preparedStmt6 = dbConnectionPool.getPreparedStmt(conn, mediaPlayLogInsert);
	    	    				preparedStmt6.setString(1, currentRouteCode);
	    	    				preparedStmt6.setString(2, mediaCode);
	    	    				preparedStmt6.setString(3, nodeCode);
	    	    				preparedStmt6.setString(4, trigger);
	    	    				preparedStmt6.setInt(5, mediaDuration);
	    	    				preparedStmt6.setString(6, relativeMediaPath);
	    	    				preparedStmt6.setString(7, playedStatus);
	    	    				preparedStmt6.setString(8, startLongLat);
	    	    				preparedStmt6.setString(9, endLongLat);
	    	    				preparedStmt6.setTimestamp(10, startTime);
	    	    				preparedStmt6.executeUpdate();
	    	    			  	preparedStmt6.close();
				    	    	preparedStmt6 = null;
				    	    	if (playCurrentMediaSet == false) // Log the remaining media in current schedule as NOT_PLAYED before starting new media set
								{
				    	    		playedStatus = NOT_PLAYED;
				    	    		for (int j = i+1; j <mediaList.length; j++)
				    	    		{
				    	    			mediaInfo = (String[]) mediaList[j];
				    	    			mediaType = mediaInfo[0];
				    	    			if (mediaType.equals(MEDIA_NORMAL))
				    	    			{
					    	    			mediaDuration = Integer.parseInt(mediaInfo[2]);
					        				mediaCode = mediaInfo[3];
					        				relativeMediaPath = mediaInfo[8];
					    	    			preparedStmt6 = dbConnectionPool.getPreparedStmt(conn, mediaPlayLogInsert);
				    	    				preparedStmt6.setString(1, currentRouteCode);
				    	    				preparedStmt6.setString(2, mediaCode);
				    	    				preparedStmt6.setString(3, nodeCode);
				    	    				preparedStmt6.setString(4, trigger);
				    	    				preparedStmt6.setInt(5, mediaDuration);
				    	    				preparedStmt6.setString(6, relativeMediaPath);
				    	    				preparedStmt6.setString(7, playedStatus);
				    	    				preparedStmt6.setString(8, endLongLat);
				    	    				preparedStmt6.setString(9, endLongLat);
				    	    				preparedStmt6.setTimestamp(10, new Timestamp(new Date().getTime()));
				    	    				preparedStmt6.executeUpdate();
				    	    			  	preparedStmt6.close();
							    	    	preparedStmt6 = null;
				    	    			}
				    	    		}
								}
				    	    	conn.close();
				    	    	conn = null;
	    	    			}
	    		    	}
    				}
    				else if (mediaType.equals(BLANK_SCREEN))
    				{
 						if (playCurrentMediaSet == true)
						{
 							synchronized(Activator.waitObject)
 							{
    							Activator.waitObject.wait(mediaDuration*1000);
    						}
    					}
    				}
    				else if (mediaType.equals(LOCATION_SCREEN))
    				{
    					conn = dbConnectionPool.getConnection();
    					preparedStmt7 = dbConnectionPool.getPreparedStmt(conn, playLocationUpdate);
	    				preparedStmt7.setString(1, "T");
	    				preparedStmt7.setInt(2, mediaDuration);
	    				preparedStmt7.executeUpdate();
	    			  	preparedStmt7.close();
		    	    	preparedStmt7 = null;
		    	    	conn.close();
		    	    	conn = null;
    					
 						if (playCurrentMediaSet == true)
						{
	    					synchronized(Activator.waitObject)
	    					{
	    						Activator.waitObject.wait(mediaDuration*1000);
	    					}
						}
    					conn = dbConnectionPool.getConnection();
	    				preparedStmt7 = dbConnectionPool.getPreparedStmt(conn, playLocationUpdate);
	    				preparedStmt7.setString(1, "F");
	    				preparedStmt7.setInt(2, 0);
	    				preparedStmt7.executeUpdate();
	    			  	preparedStmt7.close();
		    	    	preparedStmt7 = null;
		    	    	conn.close();
		    	    	conn = null;
    				}
	    			if (playCurrentMediaSet == false)
					{
	    				break whileloop;
					}
				}
    			if (loopTillNextTriggerFlag.equals("F") && playCurrentMediaSet == true)
    			{
    		    	//Wait till new media set is added to media player queue
    				synchronized(Activator.waitObject)
    				{
    					Activator.waitObject.wait();
    				}
    			}
			}
		}
    	catch (Exception e) 
		{
			log.error("Error in fetching and playing Media from queue");
    		e.printStackTrace();
			try { Thread.sleep(5000);} catch (InterruptedException e1) {}
		}
		finally
		{
			if (rs1 != null)
    		{
    			try {rs1.close();} catch (SQLException e) {} 
    			rs1 = null;
    		}
			if (rs2 != null)
    		{
    			try {rs2.close();} catch (SQLException e) {} 
    			rs2 = null;
    		}
			if (rs3 != null)
    		{
    			try {rs3.close();} catch (SQLException e) {} 
    			rs3 = null;
    		}
			if (rs4 != null)
    		{
    			try {rs4.close();} catch (SQLException e) {} 
    			rs4 = null;
    		}
    		if (preparedStmt1 != null)
    		{
    			try {preparedStmt1.close();} catch (SQLException e) {} 
    			preparedStmt1 = null;
    		}
    		if (preparedStmt2 != null)
    		{
    			try {preparedStmt2.close();} catch (SQLException e) {} 
    			preparedStmt2 = null;
    		}
    		if (preparedStmt3 != null)
    		{
    			try {preparedStmt3.close();} catch (SQLException e) {} 
    			preparedStmt3 = null;
    		}
    		if (preparedStmt4 != null)
    		{
    			try {preparedStmt4.close();} catch (SQLException e) {} 
    			preparedStmt4 = null;
    		}
    		if (preparedStmt5 != null)
    		{
    			try {preparedStmt5.close();} catch (SQLException e) {} 
    			preparedStmt5 = null;
    		}
    		if (preparedStmt6 != null)
    		{
    			try {preparedStmt6.close();} catch (SQLException e) {} 
    			preparedStmt6 = null;
    		}
    		if (preparedStmt7 != null)
    		{
    			try {preparedStmt7.close();} catch (SQLException e) {} 
    			preparedStmt7 = null;
    		}
    		if (preparedStmt8 != null)
    		{
    			try {preparedStmt8.close();} catch (SQLException e) {} 
    			preparedStmt8 = null;
    		}
			if (conn != null)
			{
				try {conn.close();} catch (SQLException e) {}
				conn = null;
			}
		}
	}
		
	private String playMedia(String file, int mediaDuration)
	{
		String playedStatus = null;
		if (mediaDuration == 0)
		{
			playedStatus = ZERO_DURATION;
			return playedStatus;
		}
		final long mediaDurationInMilliSecs = mediaDuration*1000L + 65000L;
		try
		{
			buildAndRunNewProcess(file);
			System.out.println("Started playing video");
	 		String line = null;
	 		long lastTimestamp = System.currentTimeMillis();
	 		long currentTimestamp = 0L;
	 		long elapsedTime = 0L;
	 		outer: while (true) 
            {
	 			currentTimestamp = System.currentTimeMillis();            	
            	if (mplayerStdoutRaw.available() > 0)
            	{
            		if ((line=mplayerStdOut.readLine()) != null)
            		{
            			if (line.length() == 4 && line.equals(END_OF_MEDIA_STREAM))
            			{
            				log.debug(line); 
            				if (elapsedTime < 5L)
            				{
            					playedStatus = PLAY_ERROR;
            					log.info("PLAY_ERROR :Finished playing within 5 secs!!!");
            				}
            				else
            				{
            					playedStatus = PLAYED_FULLY;
            					System.out.println("MPlayer successfully finished playing");
            				}
            				break outer;
            			}
            		}
            		else
            		{
            			log.warn("Play Status: NOt_KNOWN -Terminating mplayer process since output stream read is null even when available > 0");
            			playedStatus = NOT_KNOWN;
            			break outer;
            		} 
            	}
            	elapsedTime = currentTimestamp - lastTimestamp;
            	//System.out.println("elapsedTime: "+elapsedTime + "      mediaDurationInMilliSecs:   "+mediaDurationInMilliSecs);
        		if (playCurrentMediaSet == false)
        		{
        			System.out.println("MEDIA_INTERRUPT: Terminating mplayer process since new media set has arrived");
        			playedStatus = MEDIA_INTERRUPT;
            		break outer;
        		}
            	if(elapsedTime > mediaDurationInMilliSecs)
            	{
           			System.out.println("Play Status: NOT_KNOWN - Terminating mplayer process since elapsedTime > mediaDurationInMilliSecs ");
            		playedStatus = NOT_KNOWN;
            		break outer;
            	}
            }
		}
		catch(Exception e)
		{
			e.printStackTrace();
			playedStatus = NOT_KNOWN;
		}
		try 
		{
			Runtime.getRuntime().exec("killall -9 mplayer");
        	Thread.sleep(2000);
		} 
		catch (Exception e) {}
		return playedStatus;
	}
	
	private void buildAndRunNewProcess(String file)
	{
		try
		{
			StringTokenizer stk = new StringTokenizer(config.getMplayerCommand(), " ");
			ArrayList cmdList = new ArrayList();
			while(stk.hasMoreTokens())
			{
				cmdList.add(stk.nextToken());
			}
			cmdList.add(file);
			cmdList.add("1"); // where 1 is the queue mode
			if(mplayerProcess != null)
			{
				mplayerProcess.destroy();
				mplayerProcess = null;
			}
			if (mplayerStdoutRaw != null)
			{
				mplayerStdoutRaw.close();
				mplayerStdoutRaw = null;
			}
			if (mplayerStdOut != null)
			{
				mplayerStdOut.close();
				mplayerStdOut = null;
			}
			ProcessBuilder pb = new ProcessBuilder(cmdList);
			pb.redirectErrorStream(); 
			mplayerProcess = pb.start();
			mplayerStdoutRaw = mplayerProcess.getInputStream();
			mplayerStdOut = new BufferedReader(new InputStreamReader(mplayerStdoutRaw));
	        if (mplayerStdOut == null)
	        	throw new Exception();
	        
		}
		catch(Exception e)
		{
			System.out.println("mplayer process failed to start");
			e.printStackTrace();
		}
	}
	
	protected void stopThread()
	{
		try 
		{
			playCurrentMediaSet = false;
			running = false;
			synchronized(Activator.waitObject)
			{
				Activator.waitObject.notifyAll();
			}
			Runtime.getRuntime().exec("killall -9 mplayer");
		} catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
